package xyz.gits.modules.weread.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.gits.modules.utils.ShiroUtils;
import xyz.gits.modules.weread.entity.UnLimitPeriod;
import xyz.gits.modules.weread.mapper.UnLimitPeriodMapper;
import xyz.gits.modules.weread.service.IUnLimitPeriodService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 组队抽取无限卡周期 服务实现类
 * </p>
 *
 * @author 读钓
 * @since 2019-05-13
 */
@Slf4j
@Service
public class UnLimitPeriodServiceImpl extends ServiceImpl<UnLimitPeriodMapper, UnLimitPeriod> implements IUnLimitPeriodService {

    @Override
    public boolean init(Integer periodNum) {
        long start = System.currentTimeMillis();

        List<UnLimitPeriod> unLimitPeriodList = new ArrayList<>();
        Date now = new Date();
        IPage<UnLimitPeriod> page = baseMapper.selectPage(new Page<UnLimitPeriod>(1,1),
                new QueryWrapper<UnLimitPeriod>().lambda()
                .orderByDesc(UnLimitPeriod::getUnLimitPeriodId));
        UnLimitPeriod current = page.getRecords().get(0);

        List<UnLimitPeriod> list = new ArrayList<>(periodNum);
        LocalDateTime tempTime = current.getEndTime();
        for (int i = 0; i < periodNum; i++) {
            UnLimitPeriod entity = new UnLimitPeriod();
            entity.setUnLimitPeriodId(current.getUnLimitPeriodId() + i + 1);
            entity.setStartTime(tempTime);
            tempTime = tempTime.plusDays(7);
            entity.setEndTime(tempTime);
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
            entity.setCreateBy(ShiroUtils.getSysUser().getLoginName());
            entity.setUpdateBy(ShiroUtils.getSysUser().getLoginName());
            unLimitPeriodList.add(entity);
        }

        long end = System.currentTimeMillis();
        this.saveBatch(unLimitPeriodList);
        log.info("[初始化组队抽取无限卡] - 周期{} - {}，用时：{}毫秒", current.getUnLimitPeriodId() + 1,
                current.getUnLimitPeriodId() + periodNum, end - start);
        return true;
    }
}
